package com.starhub.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.starhub.web.host.CategoryHost;
import com.starhub.web.host.ProductHost;
import com.starhub.web.host.TileHost;
import com.starhub.web.model.Category;

public abstract class StarHubBaseController {
	
	private static final String HEADER_CATEGORIES_MODEL_ATTRIBUTE = "headerCategories";
	private static final String FOOTER_CATEGORIES_MODEL_ATTRIBUTE = "footerCategories";
	
	protected List<Category> headerCategories = new ArrayList<Category>();
	protected List<Category> footerCategories = new ArrayList<Category>();

	protected CategoryHost categoryHost;
	protected ProductHost productHost;
	protected TileHost tileHost;

	private void handleHeaderCategories(final ModelMap model) {
		if (CollectionUtils.isEmpty(headerCategories)) {
			headerCategories.addAll(categoryHost.getHeaderCategories());
			model.addAttribute(HEADER_CATEGORIES_MODEL_ATTRIBUTE, headerCategories);
		}
	}
	
	private void handleFooterCategories(final ModelMap model) {
		if (CollectionUtils.isEmpty(footerCategories)) {
			footerCategories.addAll(categoryHost.getFooterCategories());
			model.addAttribute(FOOTER_CATEGORIES_MODEL_ATTRIBUTE, footerCategories);
		}
	}
	
	protected void getCommonModel(final HttpServletRequest httpServletRequest, final ModelMap model) {
		
		handleHeaderCategories(model);
		handleFooterCategories(model);
		
		// TODO: get current category base on URI
//		String uri = httpServletRequest.getRequestURI();
//		model.addAttribute("categoryId", findCategory(headerCategories, uri).getId());
		model.addAttribute("categoryId", 5);
	}

	public void setCategoryHost(CategoryHost categoryHost) {
		this.categoryHost = categoryHost;
	}

	@ModelAttribute(value = HEADER_CATEGORIES_MODEL_ATTRIBUTE)
	public List<Category> getHeaderCategories() {
		return headerCategories;
	}
	
	@ModelAttribute(value = FOOTER_CATEGORIES_MODEL_ATTRIBUTE)
	public List<Category> getFooterCategories() {
		return footerCategories;
	}

	public void setProductHost(ProductHost productHost) {
		this.productHost = productHost;
	}

	public void setTileHost(TileHost tileHost) {
		this.tileHost = tileHost;
	}
	
	private Category findCategory(List<Category> categories, String uri) {
		for (Category category : categories) {
			if (category.getHref().contains(uri)) {
				return category;
			} else if (!CollectionUtils.isEmpty(category.getChildCategories())) {
				Category childCategory = findCategory(category.getChildCategories(), uri);
				if (childCategory != null) {
					return childCategory;
				}
			}
		}
		return null;
	}
}
